package org.example.utils;

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;

/**
 * @author Rongchang Wu
 * @version 1.0
 * @description: TODO
 * @date 2021/12/7 16:02
 */
public class JsonUtils<T>{
    /**
     * 自定义Json返回格式
     * @param resp 应答对象
     * @param dataList 数据集合
     * @param count 数据数量
     * @param <T> 泛型
     * @throws IOException
     */
    public static <T> void customJson(HttpServletResponse resp, List<T> dataList, Integer count) throws IOException {
        String json = "{}";
        ObjectMapper om = new ObjectMapper();
        json = om.writeValueAsString(dataList);
        //{
        //  "code": 0,
        //  "msg": "",
        //  "count": 1000,
        //  "data": [{}, {}]
        //}
        json = "{\"code\":0,\"msg\":\"\",\"count\":" + count + ",\"data\":" + json + "}";
        System.out.println(json);

        PrintWriter out = resp.getWriter();
        resp.setContentType("application/json;charset=utf-8");
        out.write(json);
        out.flush();
        out.close();
    }
}
